﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.ServiceModel.Syndication;
using CoolCode;
using CoolCode.Models;
using CoolCode.Services;
using CoolCode.Web;
using CoolCode.Web.Mvc;
using CoolCode.Search;
using CoolCode.Web.Syndication;
using XNoteBook.Entities;
using XNoteBook.Services;
using XNoteBook.Models;

namespace XNoteBook.UI.Controllers
{
	[HandleError]
	public class HomeController : CoolCode.Web.Mvc.ControllerBase
	{
		#region Services

		private IPostService _PostService;
		public IPostService PostService
		{
			get
			{
				if (_PostService == null)
				{
					_PostService = Digger.Dig<IPostService>();
				}
				return _PostService;
			}
		}

		static ILinqSearchEngine _searchEngine = null;

		protected ILinqSearchEngine searchEngine
		{
			get
			{
				/*Search Engine*/
				if (_searchEngine == null)
				{
					string settingFile = this.Request.MapPath("~/Config/KTDictSeg.xml");
					SegmentEngine segmentEngine = new SegmentEngine(settingFile);
					_searchEngine = new LinqSearchEngine(segmentEngine);
				}
				return _searchEngine;
			}
		}

		#endregion

		#region Home

		public ActionResult Index()
		{
			Title = "XNoteBook-知识管理系统";

			HomeIndexModel model = new HomeIndexModel();
			model.TopTenPosts.Add(this.PostService.ListTop10PostsByFrequency());
			model.TopTenPosts.Add(this.PostService.ListTop10PostsByViews());
			model.TopTenPosts.Add(this.PostService.ListTop10PostsByDate());

			return View(model);
		}

		public ActionResult Search()
		{
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get), ValidateInput(false)]
		public ActionResult Search(string q, int? page)
		{
			ViewData["starttime"] = DateTime.Now;
			Title = q + " - 搜索";
			if (q != null)
			{
				q = q.Trim();
			}
			if (string.IsNullOrEmpty(q))
			{
				return View();
			}

			if (this.HttpContext.Request.RequestType.Equals("POST", StringComparison.CurrentCultureIgnoreCase))
			{
				return RedirectToAction("Search", new { q = q, page = 0 });
			}
			else
			{
				var model = this.PostService.Search(
					q,
					page.GetValueOrDefault(),
					searchEngine,
					c => Url.FullAction("Details", "Post", new { id = c.PostID })
				);

				return View(model);
			}
		}

		public ActionResult Rss()
		{
			var rss = this.PostService.Rss();
			rss.Url = Url.FullAction("Index");
			rss.Items.ForEach(c => c.Url = Url.FullAction("Details", "Post", new { id = c.ID }));
			return new FeedResult(rss.ToSyndicationFeed(), FeedType.Rss);
		}

		public ActionResult About()
		{
			Title = "关于CoolCode";
			return View();
		}

		public ActionResult Help()
		{
			Title = "帮助";
			return View();
		}

		#endregion


		#region Login

		public ActionResult Login()
		{
			Title = "用户登录";
			LoginModel model = new LoginModel
			{
				SubTitle = "用户登录",
				RememberMe = false
			};
			return View(model);
		}

		[HttpGet]
		public ActionResult ValidateUser(LoginModel model, string returnUrl)
		{
			bool success = MembershipService.ValidateUser(model.UserName, model.Password);
			//System.Threading.Thread.Sleep(new Random().Next(4000));
			if (success)
			{
				FormsAuthenticationService.SignIn(model.UserName, model.RememberMe);
				//TODO:log who sign in the system...

				return this.Success();
			}
			else
			{
				return this.Fail("用户名或密码错误！");
			}
		}

		public ActionResult LogOff()
		{
			FormsAuthenticationService.SignOut();
			return RedirectToAction("Login");
		}

		#endregion

		#region Register

		public ActionResult Register()
		{
			initial_Register();

			return View();
		}

		[HttpPost]
		public ActionResult Register(RegisterModel model)
		{
			if (ModelState.IsValid)
			{
				// Attempt to register the user
				MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

				if (createStatus == MembershipCreateStatus.Success)
				{
					FormsAuthenticationService.SignIn(model.UserName, false /* createPersistentCookie */);
					return RedirectToAction("Index", "Home");
				}
				else
				{
					ModelState.AddModelError("", ErrorCodeToString(createStatus));
				}
			}

			initial_Register();
			// If we got this far, something failed, redisplay form
			return View(model);
		}

		private void initial_Register()
		{
			Title = "创建新用户";
			ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
		}

		private static string ErrorCodeToString(MembershipCreateStatus createStatus)
		{
			// See http://go.microsoft.com/fwlink/?LinkID=177550 for
			// a full list of status codes.
			switch (createStatus)
			{
				case MembershipCreateStatus.DuplicateUserName:
					return "Username already exists. Please enter a different user name.";

				case MembershipCreateStatus.DuplicateEmail:
					return "A username for that e-mail address already exists. Please enter a different e-mail address.";

				case MembershipCreateStatus.InvalidPassword:
					return "The password provided is invalid. Please enter a valid password value.";

				case MembershipCreateStatus.InvalidEmail:
					return "The e-mail address provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidAnswer:
					return "The password retrieval answer provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidQuestion:
					return "The password retrieval question provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidUserName:
					return "The user name provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.ProviderError:
					return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

				case MembershipCreateStatus.UserRejected:
					return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

				default:
					return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
			}
		}

		#endregion
	}
}
